package pub.guoxin.oops.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.io.IOException;

/**
 * Created by guoxin on 17-10-22.
 */
public class JsonUtils {
    private static ObjectMapper objectMapper = new ObjectMapper();

    private JsonUtils() {
    }

    public static String obj2json(Object o) {
        String jsonInString = null;
        try {
            jsonInString = objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException ignored) {
        }
        return jsonInString;
    }

    public static <T> T json2obj(String json, Class<T> clazz) {
        T obj = null;
        try {
            obj = objectMapper.readValue(json, clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static <T> T json2obj(String json, TypeReference<T> typeReference) {
        T obj = null;
        try {
            obj = objectMapper.readValue(json, typeReference);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static void main(String[] args) {
        User user = new User();
        user.setOrder(1);
        user.setPassword("2321312312");
        user.setUsername("321312312fdsafds");
        String s = JsonUtils.obj2json(user);
        System.out.println(s);
        User user1 = JsonUtils.json2obj(s, User.class);
        System.out.println(user1.toString());
    }

    @Data
    static class User {
        private String username;
        private String password;
        private int order;
    }
}
